package com.rem.se.reflect;

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

/**
 * 获取注解信息
 *
 * @author Rem
 * @date 2021-03-15
 */

public class Demo10 {

    public static void main(String[] args) throws NoSuchFieldException {

        Man man = new Man();
        Class c1 = man.getClass();
        //获取多个注解
        //Annotation[] declaredAnnotations = c1.getDeclaredAnnotations();


        boolean annotationPresent = c1.isAnnotationPresent(ClassAnno.class);
        System.out.println("是否有@ClassAnno的注解：" + annotationPresent);

        //获取某个类型的注解
        Annotation annotation = c1.getDeclaredAnnotation(ClassAnno.class);
        System.out.println("获得class上的注解" + annotation);
        ClassAnno classAnno = (ClassAnno) annotation;
        System.out.println("class上的注解的值：" + classAnno.value());


        Field name = c1.getDeclaredField("name");
        MethodAnno anno = name.getAnnotation(MethodAnno.class);
        System.out.println("单独获得：" + anno.type());

        // 字段上注解的值
        Field[] declaredFields = c1.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            MethodAnno annotation1 = declaredField.getAnnotation(MethodAnno.class);
            System.out.println(annotation1.name());
            System.out.println(annotation1.type());
            System.out.println(annotation1.length());
        }


    }
}


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface ClassAnno {

    String value();

}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface MethodAnno {

    String name();

    String type();

    int length();

}


@ClassAnno("tb_man")
class Man {

    @MethodAnno(name = "name", type = "varchar", length = 20)
    private String name;

    @MethodAnno(name = "age", type = "int", length = 4)
    private Integer age;

    @MethodAnno(name = "sex", type = "int", length = 2)
    private int sex;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public Man() {
    }

    public Man(String name, Integer age, int sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Man{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                '}';
    }
}
